#!/usr/bin/python
# - *- coding: utf-8 -*-

# ------------------------------------------------------------
## インポート
# Ptyhon
from xml.dom.minidom import parse,Element
import traceback

# ESiPC
from esipc.xml import *
from esipc.resource.iniresource import ESiPCINIFileResourceBundle

# ------------------------------------------------------------
## 変数
# ------------------------------------------------------------
## リソース変数
RESOURCE = ESiPCINIFileResourceBundle(__file__)

def put_sxb_calendar_item(items, year, month, day, site, id, text, url):
	if not items.has_key(year):
		items[year] = {}
		items[year][month] = {}
		items[year][month][day] = []
	elif not items[year].has_key(month):
		items[year][month] = {}
		items[year][month][day] = []
	elif not items[year][month].has_key(day):
		items[year][month][day] = []

	i = {}
	i["site"] = site
	i["id"] = id
	i["url"] = url
	i["text"] = text
	items[year][month][day].append(i)

def get_sxb_calendar_items(filename, url, items={}):
	element = parse(filename)

	site = ""
	try:
		site = element.getElementsByTagName("info")[0].getElementsByTagName("title")[0].firstChild.data
	except:
			pass

	nodes = element.getElementsByTagName("item")

	for item in nodes:
		title = None
		date = None
		for e in item.childNodes:
			if (isinstance(e, Element)):
				if e.tagName == "date":
					date = e.firstChild.data
				if e.tagName == "title":
					title = e.firstChild.data
		try:
			if (title != None) & (date != None):
				d = date.split("/")
				id = item.attributes["id"]
				put_sxb_calendar_item(items, int(d[0]), int(d[1]), int(d[2]), site, id.nodeValue, title, url)
		except:
			print traceback.format_exc()
			pass
	return items

def get_sxb_index_items(xml, element, items=[]):

	site = ""
	try:
		site = element.getElementsByTagName("info")[0].getElementsByTagName("title")[0].firstChild.data
	except:
			pass

	nodes = element.getElementsByTagName("index")

	for item in nodes:
		try:
			id = item.attributes["name"].nodeValue
			node = node_id(xml, "item", "id", id)
			if node != None:
				i = {}
				i["site"] = site
				i["key"] = id
				i["title"] = node.getElementsByTagName("title")[0].firstChild.data
				try:
					i["date"] = node.getElementsByTagName("date")[0].firstChild.data
				except:
					pass
				try:
					i["description"] = node.getElementsByTagName("description")[0].firstChild.data
				except:
					pass
				i["node"] = node
				items.append(i)
		except:
			pass

		else:
			if (item.hasChildNodes()):
				get_sxb_index_items(xml, item, items)
	return items

def get_sxb_index_items_from_file(filename, items=[]):
	dom1 = parse(filename)
	return get_sxb_index_items(dom1, dom1.documentElement, items)

if __name__ == '__main__':
	pass
